<?php

namespace app\shop\model\product;

use think\facade\Cache;
use \app\common\model\product\RechargeTemp as RechargeTempModel;

/**
 * 充值模板模型
 */
class RechargeTemp extends RechargeTempModel
{
    /**
     * 添加新记录
     */
    public function add($data)
    {
        $data['app_id'] = self::$app_id;
        return $this->transaction(function () use ($data) {
            $this->save($data);
            $this->addFieldList($data);
            return true;
        });
    }

    /**
     * 编辑记录
     */
    public function edit($data)
    {
        $data['app_id'] = self::$app_id;
        return $this->transaction(function () use ($data) {
            $this->save($data);
            $this->addFieldList($data);
            return true;
        });

    }

    private function addFieldList($data)
    {
        if (!isset($data["fieldList"])) {
            return true;
        }
        $this->rechargeTempDictType()->delete();
        foreach ($data["fieldList"] as $item) {
            $this->rechargeTempDictType()->save([
                "recharge_template_id" => $this["recharge_template_id"],
                "dict_id" => $item["dict_id"],
                "required" => $item["required"] ?? 0,
                "sort_order" => $item["sort_order"] ?? 0,
                "app_id" => self::$app_id,
            ]);
        }
        return true;
    }

    /**
     * 删除
     */
    public function remove($recharge_template_id)
    {
        $this->rechargeTempDictType()->where("recharge_template_id", $recharge_template_id)->delete();
        return $this->delete();
    }

    public function getDict($recharge_template_id)
    {
        $model = new RechargeTempDictType;
        return $model->getDict($recharge_template_id);
    }

}
